package com.fa.main;

import java.util.Date;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.AnnotationConfiguration;

import com.fa.role.RoleManager;

public class Main {

	private static final SessionFactory sessionFactory = buildSessionFactory();

	public static SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	public static void main(String[] args) {

		RoleManager RM = new RoleManager();

		RM.setRole_id("4");
		RM.setRole_name("sdas");
		RM.setRole_desc("sdhdshasf");
		RM.setRole_status("A");
		RM.setMaker_id("asfas");
		RM.setMake_date(new Date());
		System.out.println(new Main().addRec(RM));
	}

	/* Method to CREATE an employee in the database */
	public String addRec(RoleManager rm) {
		Session session = getSessionFactory().openSession();
		Transaction tx = null;
		String employeeID = null;
		try {
			tx = session.beginTransaction();
			employeeID = (String) session.save(rm);
			tx.commit();
		} catch (HibernateException e) {
			if (tx != null)
				tx.rollback();
			e.printStackTrace();
		} finally {
			session.close();
		}
		return employeeID;
	}

	private static SessionFactory buildSessionFactory() {
		try {
			// Create the SessionFactory from hibernate.cfg.xml
			return new AnnotationConfiguration().configure().addAnnotatedClass(RoleManager.class)
					.buildSessionFactory();

		} catch (Throwable ex) {
			// Make sure you log the exception, as it might be swallowed
			System.err.println("Initial SessionFactory creation failed." + ex);
			throw new ExceptionInInitializerError(ex);
		}
	}

	public static void shutdown() {
		// Close caches and connection pools
		getSessionFactory().close();
	}
}
